package com.tju.hotel.hotel.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tju.hotel.R;
import com.tju.hotel.hotel.MyApplication;
import com.tju.hotel.hotel.bean.MemberBean;
import com.tju.hotel.hotel.util.DeviceUtils;
import com.tju.hotel.hotel.util.MD5Util;
import com.tju.hotel.hotel.util.OkHttpTool;
import com.tju.hotel.hotel.util.SPUtils;
import com.tju.hotel.hotel.util.ServiceUrls;
import com.tju.hotel.hotel.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {


    private  final String TAG="LIFE LoginActivity";

    //
    private Activity mActivityContext;
    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    private MyApplication myApplication;

    //控件
    private Button btnSubmit;//登录按钮
    private LinearLayout llSms;//容器 短信验证码登录
    private LinearLayout llPassword;//容器-按钮 密码登录
    private TextView tvSms;//文本-按钮 验证码登录
    private TextView tvPassword;//文本-按钮 密码登录
    private TextView tvRegister;//文本-按钮 去注册页面
    private TextView tvForgetPassword;//文本-按钮 去忘记密码页面
    private EditText etPhone;//文本框 手机号
    private EditText etSmsCode;//文本框 验证码
    private EditText etPassword;//文本框 密码
    private TextView tvSendSms;//文本-按钮 发送验证码

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate");

        mActivityContext = LoginActivity.this;
        myApplication= (MyApplication) getApplication();
        //设置布局
        setContentView(R.layout.activity_login);

        //获取控件
        btnSubmit = findViewById(R.id.btn_login_submit);
        llSms = findViewById(R.id.ll_login_sms);
        llPassword = findViewById(R.id.ll_login_password);
        tvSms = findViewById(R.id.tv_login_sms);
        tvPassword = findViewById(R.id.tv_login_password);
        tvRegister = findViewById(R.id.tv_login_register);
        tvForgetPassword = findViewById(R.id.tv_login_forget_password);
        etPhone = findViewById(R.id.et_login_phone);
        etSmsCode = findViewById(R.id.et_login_sms_code);
        etPassword = findViewById(R.id.et_login_password);
        tvSendSms = findViewById(R.id.tv_login_send_sms);

        //设置控件事件
        setViewListener();


    }

    //设置控件事件

    private void setViewListener() {

        //文本-按钮 注册新会员 点击事件
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //意图 参数：context，要打开的页面的类.class
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                //打开activity
                startActivity(intent);
                finish();//关闭并销毁当前activity
            }
        });

        //文本-按钮 重置密码 点击事件
        tvForgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
                startActivity(intent);
            }
        });

        //文本-按钮 密码登录  点击事件
        tvPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示 密码登录输入框
                llPassword.setVisibility(View.VISIBLE);
                //显示 文本-按钮用验证码登录
                tvSms.setVisibility(View.VISIBLE);
                //隐藏短信验证码输入框
                llSms.setVisibility(View.GONE);
                //隐藏 文本-按钮 密码登录
                tvPassword.setVisibility(View.GONE);
            }
        });

        //文本-按钮用验证码登录 点击事件
        tvSms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llPassword.setVisibility(View.GONE);
                tvSms.setVisibility(View.GONE);
                llSms.setVisibility(View.VISIBLE);
                tvPassword.setVisibility(View.VISIBLE);
            }
        });

        //获取验证码
        tvSendSms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取手机号
                String phone = etPhone.getText() == null ? "" : etPhone.getText().toString();
                //验证数据
                if (!Tools.isMobile(phone)) {
                    etPhone.setError("请输入正确的手机号");
                    return;
                }
                //禁用发送按钮
                tvSendSms.setEnabled(false);
                //获取设备ID
                String deviceId = DeviceUtils.getDeviceUUID(mActivityContext);
                //==发送请求
                //url
                String url = ServiceUrls.getMemberMethodUrl("sendSmsValid");
                //参数
                Map<String, Object> map = new HashMap<>();
                map.put("phone", phone);
                map.put("deviceId", deviceId);
                map.put("isRegister", false);
                //发送请求
                OkHttpTool.httpPost(url, map, new OkHttpTool.ResponseCallback() {
                    @Override
                    public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
                        //需要更新UI，所有要在UI线程中执行
                        mActivityContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (isSuccess && responseCode == 200) {
                                    //重新发送倒计时 60s 步长1s
                                    CountDownTimer timer = new CountDownTimer(60 * 1000, 1000) {
                                        //每一步的回调
                                        @Override
                                        public void onTick(long millisUntilFinished) {
                                            tvSendSms.setText(String.format(Locale.getDefault(), "重新获取(%1$d)", (millisUntilFinished / 1000)));
                                        }

                                        //定时器执行完成的回调
                                        @Override
                                        public void onFinish() {
                                            tvSendSms.setEnabled(true);//启用发送按钮
                                            tvSendSms.setText("获取验证码");
                                        }
                                    };
                                    //启动定时器
                                    timer.start();

                                    //解析服务端返回数据
                                    try {
                                        //json对象 获取code
                                        JSONObject jsonObject = new JSONObject(response);
                                        int code = jsonObject.getInt("code");
                                        if (code == 200) {
                                            //发送成功
                                            Toast.makeText(mActivityContext, "验证码发送成功，请注意查收", Toast.LENGTH_LONG).show();
                                        } else {
                                            //发送失败 json.text中存放发送失败原因
                                            String text = jsonObject.getString("text");
                                            if (code == 404) {
                                                etPhone.setError(text);
                                            }
                                            Toast.makeText(mActivityContext, text, Toast.LENGTH_LONG).show();
                                        }
                                        return;
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                Toast.makeText(mActivityContext, "验证码发送失败，请稍后再试", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                });
            }
        });

        //匿名内部实现类
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(LoginActivity.this,"提示：你点击了按钮, 匿名内部实现类",Toast.LENGTH_LONG).show();
                //获取参数
                String phone = etPhone.getText() == null ? "" : etPhone.getText().toString();
                String smsValidCode = etSmsCode.getText() == null ? "" : etSmsCode.getText().toString();
                String password = etPassword.getText() == null ? "" : etPassword.getText().toString();

                boolean isSmsLogin = llSms.getVisibility() == View.VISIBLE;
                //验证数据
                if (!Tools.isMobile(phone)) {
                    etPhone.setError("请输入正确的手机号");
                    return;
                }
                //在短信登录的情况下验证验证码
                if (isSmsLogin && !Tools.isNotNull(smsValidCode)) {
                    etSmsCode.setError("请输入验证码");
                    return;
                }
                //在密码登录情况下验证密码是否为空
                if (!isSmsLogin && !Tools.isNotNull(password)) {
                    etPassword.setError("请输入密码");
                    return;
                }
                //==发送请求
                //url
                String url = isSmsLogin ? ServiceUrls.getMemberMethodUrl("loginBySms") : ServiceUrls.getMemberMethodUrl("loginByPassword");
                //参数
                Map<String, Object> map = new HashMap<>();
                map.put("phone", phone);
                if (isSmsLogin) {
                    map.put("smsValidCode", smsValidCode);
                } else {
                    map.put("password", MD5Util.getMD5(password));
                }
                //发送请求
                OkHttpTool.httpPost(url, map, new OkHttpTool.ResponseCallback() {
                    @Override
                    public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
                        mActivityContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String strText = "无法访问服务器，请检查网络连接";
                                if (isSuccess && responseCode == 200) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        int code = jsonObject.getInt("code");
                                        strText = jsonObject.getString("text");
                                        if (code == 200) {
                                            String strData = jsonObject.getString("data");
                                            MemberBean memberBean = gson.fromJson(strData, MemberBean.class);
                                            if(memberBean!=null){
                                                //将用户信息保存到Application中
                                                myApplication.setLoginMember(memberBean);
                                                //将phone和password存入SharedPreferences
                                                SPUtils.put(mActivityContext, ServiceUrls.SP_MEMBER_PHONE, memberBean.getPhone().trim());
                                                SPUtils.put(mActivityContext, ServiceUrls.SP_MEMBER_PASSWORD, memberBean.getPassword().trim());
                                            }else{
                                                strText = "登录失败";
                                            }
                                            Log.d("登录",memberBean.getMemberName());

                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                Toast.makeText(mActivityContext, strText, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                });

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG,"onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG,"onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG,"onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy");
    }
}